package com.jk.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jk.model.*;
import com.jk.service.ZSLService;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("zsl")
public class ZSLController<DataGridResult> {

    @Reference(check = false,timeout = 100000)
    private ZSLService zslService;

    /**
     * 注入mongodb
     */
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 加入购物车  mongodb
     * @param productId
     * @param request
     * @return
     */
    @RequestMapping("saveShop")
    @ResponseBody
    public Map saveShop(Integer productId,HttpServletRequest request,Integer count){
        HashMap<String, Object> result = new HashMap<>();
        HttpSession session = request.getSession();
        UserBean attribute = (UserBean) session.getAttribute(session.getId());
        if (attribute == null){
            result.put("code",1);
            result.put("msg","请登录");
            return null;
        }
        //Integer count=2;
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(attribute.getId()));
        query.addCriteria(Criteria.where("productId").is(productId));
        ShopBean shopBeans = mongoTemplate.findOne(query, ShopBean.class);
        if (shopBeans == null){
            ShopBean shopBean = new ShopBean();
            shopBean.setCreateTime(new Date().toString());
            shopBean.setProductId(productId);
            shopBean.setUserId(attribute.getId());
            shopBean.setCount(count);
            mongoTemplate.save(shopBean);
        }else {
            Query query1 = new Query();
            query1.addCriteria(Criteria.where("id").is(shopBeans.getId()));
            Update update = new Update();
            update.set("count",shopBeans.getCount()+count);
            mongoTemplate.updateFirst(query1,update,ShopBean.class);
        }

        result.put("code",0);
        result.put("msg","加入成功");

        return result;
    }

    /**
     * 模拟购物车数据
     * @param request
     * @return
     */
    @RequestMapping("shopping")
    @ResponseBody
    public Map shopping(HttpServletRequest request){
        HashMap<String, Object> result = new HashMap<>();
        HttpSession session = request.getSession();
        UserBean user = (UserBean) session.getAttribute(session.getId());
        if (user == null){
            result.put("code",1);
            result.put("msg","请登录");
            return result;
        }
        Integer id = user.getId();
        //String id ="1";
        Query query = new Query();

        query.addCriteria(Criteria.where("userId").is(id));
        List<ShopBean> shopBeans = mongoTemplate.find(query, ShopBean.class);
        ArrayList<ProductBean> list = new ArrayList<>();
        for (ShopBean shopBean : shopBeans) {
            ProductBean productBean=zslService.queryProductByProductId(shopBean.getProductId());
            productBean.setShopCarId(shopBean.getId());
            productBean.setCount(shopBean.getCount());
            list.add(productBean);
        }
        result.put("rows",list);
        return result;
    }

    /**
     * 删除购物车数据
     * @param id
     */
    @RequestMapping("delShopCar")
    @ResponseBody
    public void delShopCar(String id){
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        mongoTemplate.remove(query,ShopBean.class);
    }

    /**
     * 支付成功，修改订单
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("adddingdan")
    @ResponseBody
    public Boolean adddingdan(HttpServletRequest request,Integer id){
        try {

            /*String zhifuzhuangtai = Commonfig.ZHIFUZHUANGTAI+1;
            String o = redisTemplate.opsForValue().get(zhifuzhuangtai).toString();
            //String s = JSON.toJSONString(o);
            List<OrderBean> orderBeans = JSONArray.parseArray(o, OrderBean.class);
            ArrayList<OrderBean> orderBeanArrayList = new ArrayList<>();
            for (OrderBean orderBean : orderBeans) {
                OrderBean orderBean1 = new OrderBean();
                //订单号
                orderBean1.setOrderNo(orderBean.getOrderNo());
                //商品数量
                orderBean1.setProductCount(orderBean.getProductCount());
                //总价格
                orderBean1.setOrderPrice(orderBean.getOrderPrice());
                //订单创建时间
                orderBean1.setOrderCreateTime(orderBean.getOrderCreateTime());
                //订单状态
                orderBean1.setOrderStatus(2);
                //商品id
                orderBean1.setProductId(orderBean.getProductId());
                //用户id
                orderBean1.setUserId(1);
                //收货地址
                orderBean1.setAcceptstiseId(id);
                orderBeanArrayList.add(orderBean1);
            }
            redisTemplate.opsForList().rightPush("shopping"+1,orderBeanArrayList);
            //zslService.adddingdan(orderBeanArrayList);*/
            HttpSession session = request.getSession();
            session.setAttribute("dizhi",id);
            /*List<OrderBean> dingdan  = (List<OrderBean>) session.getAttribute("dingdan");
            ArrayList<OrderBean> orderBeanArrayList = new ArrayList<>();
            for (OrderBean orderBean : dingdan) {
                OrderBean orderBean1 = new OrderBean();
                //收货地址
                orderBean1.setAcceptstiseId(id);
                orderBeanArrayList.add(orderBean1);
            }
            zslService.updateOrder(orderBeanArrayList)*/;
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 支付成功，跳转页面
     * @param request
     * @return
     */
    @RequestMapping("dingdan1")
    public String dingdan1(HttpServletRequest request){
        HttpSession session = request.getSession();
        List<OrderBean> dingdan  = (List<OrderBean>) session.getAttribute("dingdan");
        Integer id = (Integer) session.getAttribute("dizhi");
        for (int i = 0; i < dingdan.size(); i++) {
            zslService.updateOrder(dingdan.get(i).getOrderNo(),id);
        }
        UserBean user = (UserBean) session.getAttribute(session.getId());
        Query query = new Query();
        Integer[] productId = (Integer[]) session.getAttribute("productId");
        for (Integer integer : productId) {
            query.addCriteria(Criteria.where("product").is(integer));
            query.addCriteria(Criteria.where("userId").is(user.getId()));
            mongoTemplate.remove(query,ShopBean.class);
        }
        /*ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("page/shopCar");*/
        return "discount/Zhuyemian.html";
    }

    /**
     * 根据订单查询订单中的商品
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("chajiaoyi")
    public List<OrderBean> chajiaoyi(HttpServletRequest request){
        HttpSession session = request.getSession();
        /*UserBean user = (UserBean) session.getAttribute(session.getId());
        String zhifuzhuangtai = Commonfig.ZHIFUZHUANGTAI+1;
        String o = redisTemplate.opsForValue().get(zhifuzhuangtai).toString();
        //String s = JSON.toJSONString(o);
        List<OrderBean> orderBeans = JSONArray.parseArray(o, OrderBean.class);
        List<OrderBean> row=new ArrayList<>();
        for (OrderBean orderBean : orderBeans) {
            OrderBean order = zslService.chajiaoyi(orderBean.getProductId());
            order.setOrderPrice(orderBean.getOrderPrice());
            order.setProductCount(orderBean.getProductCount());
            order.setOrderNo(orderBean.getOrderNo());
            row.add(order);
        }*/
        List<OrderBean> dingdan  = (List<OrderBean>) session.getAttribute("dingdan");
        List<OrderBean> row=new ArrayList<>();
        for (OrderBean orderBean : dingdan) {
            OrderBean order = zslService.chajiaoyi(orderBean.getProductId());
            order.setOrderPrice(orderBean.getOrderPrice());
            order.setProductCount(orderBean.getProductCount());
            order.setOrderNo(orderBean.getOrderNo());
            row.add(order);
        }
        return row;
    }

    /**
     * 查询收货地址
     * @param request
     * @return
     */
    @RequestMapping("chaaddress")
    @ResponseBody
    public Map chaaddress(HttpServletRequest request){
        HttpSession session = request.getSession();
        UserBean attribute = (UserBean) session.getAttribute(session.getId());
        List<AcceptsiteBean> row = zslService.chaAddress(attribute.getId());
        HashMap<String, Object> result = new HashMap<>();
        result.put("rows",row);
        return result;
    }

    /**
     * 删除收获地址
     * @param id
     * @return
     */
    @RequestMapping("deleteaddress")
    @ResponseBody
    public Boolean deleteaddress(Integer id){
        try {
            zslService.deleteaddress(id);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 新增收货地址or
     * 修改
     * @param acceptsiteBean
     * @param request
     * @return
     */
    @RequestMapping("addressdizhi")
    @ResponseBody
    public Boolean addressdizhi(AcceptsiteBean acceptsiteBean,HttpServletRequest request){
        try {
            if (acceptsiteBean.getId()==null){
                HttpSession session = request.getSession();
                UserBean user = (UserBean) session.getAttribute(session.getId());
                acceptsiteBean.setUserId(user.getId());
                zslService.addressdizhi(acceptsiteBean);
            }else {
                zslService.addressdizhiUpdate(acceptsiteBean);
            }

            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 跳转支付页面
     * @param request
     * @return
     */
    @RequestMapping("zhifuyemian")
    public ModelAndView zhifuyemian(HttpServletRequest request){
        HttpSession session = request.getSession();
        UserBean user = (UserBean) session.getAttribute(session.getId());
        List<OrderBean> orderBeans = (List<OrderBean>) session.getAttribute("dingdan");
        /*String zhifuzhuangtai = Commonfig.ZHIFUZHUANGTAI+1;
        String o = redisTemplate.opsForValue().get(zhifuzhuangtai).toString();
        List<OrderBean> orderBeans = JSON.parseArray(o, OrderBean.class);*/
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("shoppIng/cha");
        for (OrderBean orderBean : orderBeans) {
            modelAndView.addObject("ordernumber",orderBean);
        }
        return modelAndView;
    }

    /**
     * 生成订单
     * @param productid
     * @param count
     * @param productprice
     * @param request
     * @return
     */
    @RequestMapping("saveOrder")
    @ResponseBody
    public Boolean saveOrder(Integer[] productid,Integer[] count,double[] productprice,HttpServletRequest request){
        try {
            HttpSession session = request.getSession();
            UserBean user = (UserBean) session.getAttribute(session.getId());
            session.setAttribute("productId",productid);
            ArrayList<OrderBean> objects1 = new ArrayList<>();
            //ArrayList<OrderBean> objects = new ArrayList<>();
            for (int i = 0; i < productid.length; i++) {
                OrderBean orderBean = new OrderBean();
                long round = Math.round((Math.random() * 9 + 1) * 100000);
                //时间戳
                long timeMillis = System.currentTimeMillis();
                orderBean.setOrderNo(String.valueOf(timeMillis)+round+user.getId());
                //用户id
                orderBean.setUserId(user.getId());
                //商品id
                orderBean.setProductId(productid[i]);
                //商品数量
                orderBean.setProductCount(count[i]);
                //商品总价
                orderBean.setOrderPrice(productprice[i]*count[i]);
                //付款状态 默认为1
                orderBean.setOrderStatus(1);
                //创建时间
                Date date = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateString = formatter.format(date);
                orderBean.setOrderCreateTime(dateString);
                objects1.add(orderBean);
                //减少库存
                zslService.updateNumber(productid[i],count[i]);
            }
            session.setAttribute("dingdan",objects1);
            zslService.adddingdan(objects1);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 查询树
     * @return
     */
    @RequestMapping("findManageTree")
    @ResponseBody
    public List<ManageBean> findManageTree(){
        List<ManageBean> manageTree = zslService.findManageTree();
        return manageTree;
    }

    /**
     * 查询用户信息
     * @param page
     * @param rows
     * @param userBean
     * @return
     */
    @RequestMapping("findUserList")
    @ResponseBody
    public Map findUserList(Integer page, Integer rows, UserBean userBean){
        return zslService.findUserList(page,rows,userBean);
    }

    /**
     * 删除用户信息
     * @param ids
     * @return
     */
    @RequestMapping("delUserById")
    @ResponseBody
    public Boolean delUserById(Integer[] ids){
        try {
            zslService.delUserById(ids);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 通过用户id查询所拥有的店铺
     * @param page
     * @param rows
     * @param userBean
     * @return
     */
    @RequestMapping("findUserShopList")
    @ResponseBody
    public Map findUserShopList(Integer page, Integer rows, UserBean userBean){
        return zslService.findUserShopList(page,rows,userBean);
    }

    /**
     * 审核店铺的页面
     * @param page
     * @param rows
     * @param userBean
     * @return
     */
    @RequestMapping("findShopUserList")
    @ResponseBody
    public Map findShopUserList(Integer page, Integer rows, UserBean userBean){
        Map shopUserList = zslService.findShopUserList(page, rows, userBean);
        return shopUserList;
    }

    /**
     * 商家所拥有的商品
     * @param page
     * @param rows
     * @param productBean
     * @param id
     * @return
     */
    @RequestMapping("shopTable")
    @ResponseBody
    public Map shopTable(Integer page, Integer rows, ProductBean productBean, Integer id){
        return zslService.shopTable(page,rows,productBean,id);
    }

    /**
     * 查询所有订单信息
     * @param page
     * @param rows
     * @param orderBean
     * @return
     */
    @RequestMapping("findOrderList")
    @ResponseBody
    public Map findOrderList(Integer page, Integer rows, OrderBean orderBean){
        return zslService.findOrderList(page,rows,orderBean);
    }

    /**
     * 根据店铺商品查询订单
     * @param page
     * @param rows
     * @param orderBean
     * @param id
     * @return
     */
    @RequestMapping("orderTable")
    @ResponseBody
    public Map orderTable(Integer page, Integer rows, OrderBean orderBean,Integer id){
        return zslService.orderTable(page, rows, orderBean, id);
    }

    /**
     * 根据店铺商品查询订单
     * @param page
     * @param rows
     * @param orderBean
     * @param id
     * @return
     */
    @RequestMapping("findOrder")
    @ResponseBody
    public Map findOrder(Integer page, Integer rows, OrderBean orderBean,Integer id){
        return zslService.findOrder(page, rows, orderBean, id);
    }

    /**
     * 定时器修改订单
     * @throws ParseException
     */
    @Scheduled(cron = "0 0/5 * * * ?") //每5分钟调用一次方法 0 0/5 * * * ?
    public void testTasks2() throws ParseException {
        long time = new Date().getTime();  //获取当前时间毫秒值
        long time3 = time-(1000*60*30);
        System.out.println("五分钟已过");
        //当前时间-30分钟
        long time5 = time - time3;
        Date date = new Date();
        date.setTime(time3);
        //数据库查询订单未付款的
        List<OrderBean> list=zslService.findOrderByStart();
        for (OrderBean orderBean : list) {
            //获取创建订单时间
            String orderCreateTime = orderBean.getOrderCreateTime();
            //转date格式
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date parse = formatter.parse(orderCreateTime);
            //转为毫秒值
            long time1 = parse.getTime();
            //当前时间-创建时间
            long date1 = time - time1;
            if (date1 > time5){
                //修改订单状态 改为未付款
                zslService.updateOrderById(orderBean.getId());
                //修改库存
                zslService.updateNumberByOrder(orderBean.getProductId(),orderBean.getProductCount());
            }
        }
    }


    /*@RequestMapping("findOrder")
    @ResponseBody
    public Map findOrder(OrderBean orderBean,Integer page, Integer rows){
        return zslService.orderTable(orderBean,page,rows);
    }*/

}
